# from photo_services import *

import sys
try:
    from flickrapi import FlickrAPI
except ImportError:
    sys.exit('Beej\'s Python Flickr API not found: http://beej.us/flickr/flickrapi/')
    raise 

# class FlickrPhotoService(AbstractPhotoService):
class FlickrPhotoService:
    def __init__(self):
        self.service = self._login()
    
    def _login(self):
        """
        Performs user authentication and returns service object if successful
        """
        # flickr auth information:
        self.fapikey = "f3f460f0c95607acf33fc1296b3e9645"  # API key
        self.fapisecret = "cc2ede1bd2305581"                  # shared "secret"

        # make a new FlickrAPI instance
        self.fapi = FlickrAPI(self.fapikey, self.fapisecret)

        # do the whole whatever-it-takes to get a valid token:
        self.fapitoken = self.fapi.getToken(browser="firefox")


    def get_sets(self):
        rsp = self.fapi.photosets_getList(api_key=self.fapikey, auth_token=self.fapitoken)
        self.fapi.testFailure(rsp)
        sets = [
        {
            'id': s['id'],
            'count': int(s['photos']),
            'title': s.title[0].elementText,
            'description': s.description[0].elementText,
        }
        for s in rsp.photosets[0].photoset]
        
        return sets
    
    def get_photos(self, current_set):
        rspPhotos = self.fapi.photosets_getPhotos(api_key=self.fapikey, photoset_id=current_set['id'])
        self.fapi.testFailure(rspPhotos)
        photos = []
        for p in rspPhotos.photoset[0].photo:
            photo = {
                'id': p['id'],
                'title': p['title'],
            }
            # now to get info about the picture
            rspPhoto = self.fapi.photos_getInfo(api_key=self.fapikey, photo_id=photo['id'])
            self.fapi.testFailure(rspPhoto)
            photo.update(
                description = rspPhoto.photo[0].description[0].elementText,
                tags = [tag['raw'] for tag in rspPhoto.photo[0].tags[0].tag],
            )
            # now to get url to the original image
            rspPhoto = self.fapi.photos_getSizes(api_key=self.fapikey, photo_id=photo['id'])
            self.fapi.testFailure(rspPhoto)
            photo.update(
                url = [size['url'] for size in rspPhoto.sizes[0].size if size['label'] == 'Original'][0],
            )
            photos.append(photo)
        return photos

    def download_photos(self):
        sets = self._get_sets()
        for s in sets:
            s.photos = self._get_photos(s)
        
        return sets

    def upload_photos(self, sets):
        raise NotImplementedError


if __name__ == "__main__":
    fps = FlickrPhotoService()
    sets = fps.get_sets()
    photos = fps.get_photos(sets[0])
    print sets
    print photos